package cn.TcpService;

import java.util.Timer;
import java.util.TimerTask;

import cn.tcp.TcpNewUtil;
import cn.tcpTask.SwitchTask;

public class CoilTask extends TimerTask {

	private static Timer timer;
	private int decid;
	private int switchid;
	private long delay;
	private boolean writeValue;
	private String host;
	private boolean flag = true;
	private CoilSchedule cs;
	private int CurrentSwitchid;
	private TcpNewUtil tnu;
	private CoilSchedule PreviousCoil;

	/**
	 * 
	 * @param host
	 *            主机
	 * @param deviceID
	 *            节点ID
	 * @param switchID
	 *            开关通道ID
	 * @param wirteValue
	 *            写入值
	 * @param delay
	 *            多久后开始执行。
	 */
	public CoilTask(String host, int deviceID, int switchID,
			boolean wirteValue, long delay) {
		this.decid = deviceID;
		this.switchid = switchID;
		this.delay = delay;
		this.host = "192.168.1.122";
		this.writeValue = wirteValue;
		tnu = new TcpNewUtil();
	}

	public CoilTask(CoilSchedule cs) {
		this.cs = cs;
	}

	public boolean startSwitchTask(CoilSchedule PreviousCoil) {
		try {
			// 获取执行前的当前时间
			System.out.println("    正在执行打开关");
			timer = new Timer();
			CoilTask mt = new CoilTask(host, cs.getDecid(), cs.getSwitchid(),
					cs.isWriteValue(), cs.getDelay());
			timer.schedule(mt, 0);

			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void run() {

		try {
		    //只有这个执行成功了。才能去关闭上一个
			boolean flag = tnu.ControlSwitch(decid, switchid, writeValue);
			// 不等于null的时候执行，等于null的时候，说明是第一个
			if (flag) {
				if (PreviousCoil != null)
					//关闭上一个开关
					tnu.ControlSwitch(PreviousCoil.getDecid(), PreviousCoil.getSwitchid(), false);
				    System.out.println("   正在关闭开关");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean isFlag() {
		return flag;
	}

}
